package com.polaris.live.widget.base_view

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Matrix
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import com.polaris.live.R
import com.polaris.live.common.util.AppCodeUtils

/**
 * 自适应textView      如果是正常的图片比如webp或者什么png什么的图片并且是textView 用这个就好
 *
 * @author Created by 半仙 on 2023/12/22/022 15:17
 */
class AdaptiveTextView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0,
) : AppCompatTextView(context, attrs, defStyleAttr) {

    private var customBackground: Drawable? = null

    private var newBitmap: Bitmap? = null

    init {
        obtainCustomAttributes(attrs)
        setDrawable()
    }

    private fun setDrawable() {
        if (customBackground == null) return

        if (AppCodeUtils.isAR()) {
            val bitmap = drawableToBitmap(customBackground!!)
            newBitmap = buildBitmap(bitmap)
            val tempDrawable = BitmapDrawable(resources, newBitmap)
            this.background = tempDrawable
        } else {
            this.background = customBackground
        }

    }

    private fun obtainCustomAttributes(attrs: AttributeSet?) {
        if (attrs == null) {
            return
        }

        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.AdaptiveTextView)
        customBackground = typedArray.getDrawable(R.styleable.AdaptiveTextView_backgroundSrc)
        typedArray.recycle()
    }

    private fun drawableToBitmap(drawable: Drawable): Bitmap {

        if (drawable is BitmapDrawable) {
            if (drawable.bitmap != null) {
                return drawable.bitmap
            }
        }

        val bitmap: Bitmap = if (drawable.intrinsicWidth <= 0 || drawable.intrinsicHeight <= 0) {
            Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888)
        } else {
            Bitmap.createBitmap(
                drawable.intrinsicWidth,
                drawable.intrinsicHeight,
                Bitmap.Config.ARGB_8888
            )
        }

        val canvas = Canvas(bitmap)
        drawable.setBounds(0, 0, canvas.width, canvas.height)
        drawable.draw(canvas)

        return bitmap
    }

    private fun buildBitmap(bitmap: Bitmap): Bitmap {
        val matrix = Matrix()
        matrix.setScale(-1f, 1f)
        return Bitmap.createBitmap(
            bitmap,
            0, 0, bitmap.width, bitmap.height,
            matrix, true
        )
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        newBitmap?.recycle()
    }
}